import Koa, { Context, Next } from 'koa';
import cors from 'koa2-cors';
import bodyParser from 'koa-bodyparser'
import router from '@/routes/index';
import viewsRouter from '@/routes/views.router';

import { config } from './config/env';
import Database from './config/database';
import errorMiddleware from './middleware/error';
import swaggerUIMiddleware from './middleware/swagger';
import { AppDataSource } from './config/AppDataSource';
import serve from 'koa-static';
import path from 'path';
import sessionConfig from './config/session.config';
import session from 'koa-session';

(async () => {

    // 不这样处理的话，数据库存储的日期是 2025-06-09 10:26:52，查出来会变 2025-06-09T02:26:52.000Z
    Date.prototype.toJSON = function () {
        // 保持原有时区不转为UTC
        const timezoneOffset = this.getTimezoneOffset() * 60000;
        return new Date(this.getTime() - timezoneOffset).toISOString().slice(0, 19).replace('T', ' ');
    };
    //使用orm连接
    try {
        await AppDataSource.initialize()
        console.log("orm连接成功")
    } catch (e) {
        console.log("orm连接失败---", e)
    }


    // console.log("ormres",ormres)
    //连接数据库
    // await Database.initialize()
    const app = new Koa();
    //设置key，session 需要用
    app.keys = [config.app.key]
    // 跨域
    // 允许的域名列表
    const ALLOWED_ORIGINS = [
        'http://localhost:3000',
        'http://localhost:3001',
        'https://your-production-domain.com'
    ];



    // CORS 配置
    app.use(cors({
        origin: (ctx) => {
            const requestOrigin = ctx.get('Origin');
            return requestOrigin;
            if (ALLOWED_ORIGINS.includes(requestOrigin)) {
                return requestOrigin;
            }
            return false;
        },

        credentials: true,
        allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
        allowHeaders: ['Content-Type', 'authorizationtoken','x-requested-with']
    }));
    //计算响应时间
    app.use(async (ctx, next) => {
        const start = Date.now(); // 记录开始时间
        await next(); // 执行后续中间件和路由
        const ms = Date.now() - start; // 计算耗时（毫秒）
        ctx.set('X-Response-Time', `${ms}ms`); // 设置响应头
        // console.log(`请求 ${ctx.url} 耗时 ${ms}ms`);

    })
    app.use(session(sessionConfig, app));

    // 静态文件服务
    app.use(serve(path.join(__dirname, '../public')));

    //到时候会去掉，现在这个相当于存在项目外面的
    app.use(serve(path.join(__dirname, '../../public')));

    // app.use(async (ctx: Context, next: Next) => {
    //     ctx.setBody = (data: any, code = 200, message: "") => {
    //         ctx.body = {
    //             data,
    //             code,
    //             message
    //         }
    //     }
    //     await next()
    // })
    app.use(errorMiddleware);
    // 解析请求体
    app.use(bodyParser())
    // Swagger 文档
    app.use(swaggerUIMiddleware);

    // 响应
    app.use(router.routes()).use(router.allowedMethods());
    app.use(viewsRouter.routes()).use(viewsRouter.allowedMethods());


    const PORT = config.app.port;
    const server = app.listen(3000, async () => {
        console.log(`http://localhost:${PORT}/`);
    });
    process.on('SIGTERM', async () => {
        // await Database.close();
        server.close(() => {
            console.log('Server closed');
            process.exit(0);
        });
    });


})()

